<template>
    <div class="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100 p-4 md:p-8">
        <div class="max-w-7xl mx-auto">
            <header class="mb-8">
                <h1 class="text-[clamp(1.75rem,3vw,2.5rem)] font-bold text-gray-800 mb-2">文档切片列表</h1>
                <p class="text-gray-600">展示知识文档的切片内容</p>
                <button @click="handleAddNew"
                    class="bg-green-500 hover:bg-green-600 text-white font-medium py-2 px-4 rounded-lg transition-colors duration-300 flex items-center shadow-lg">
                    <i class="fa fa-plus mr-2"></i>
                    <span>新增切片</span>
                </button>
            </header>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <div v-for="(slice, index) in splitterList" :key="slice.id"
                    class="bg-white rounded-xl shadow-lg overflow-hidden transform transition-all duration-300 hover:shadow-xl hover:-translate-y-1">
                    <div class="p-6">
                        <div class="flex justify-between items-start mb-4">
                            <h2 class="text-xl font-semibold text-gray-800">{{ slice.title }}</h2>
                            <span class="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
                                ID: {{ index + 1 }}
                            </span>
                        </div>
                        <div class="prose max-w-none text-gray-700 mb-6">
                            <p class="line-clamp-4">{{ slice.content }}</p>
                        </div>

                        <div class="flex justify-between">
                            <!--删除确认框-->
                            <button
                                class="bg-red-400 hover:bg-red-500 text-white font-medium py-2 px-4 rounded-lg transition-colors duration-300 flex items-center"
                                @click="handleDelete(slice.id)">
                                <span>删除</span>
                                <i class="fa fa-arrow-right ml-2"></i>
                            </button>
                            <button
                                class="bg-blue-500 hover:bg-blue-600 text-white font-medium py-2 px-4 rounded-lg transition-colors duration-300 flex items-center"
                                @click="handleViewDetails(index)">
                                <span>查看详情</span>
                                <i class="fa fa-arrow-right ml-2"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="demo-pagination-block mt-3">
                <el-pagination v-model:current-page="splitterPageQueryDTO.page" style="justify-content: center;"
                    v-model:page-size="splitterPageQueryDTO.pageSize" :page-sizes="[6, 9, 12, 15]" :size="'large'"
                    :disabled="false" :background="false" layout="total, sizes, prev, pager, next, jumper"
                    :total="splitterTotalCnt" @size-change="getSplitters" @current-change="getSplitters" />
            </div>
        </div>
        <!-- 详情/编辑模态框 -->
        <div v-if="showDetail"
            class="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 modal-transition"
            @click.self="closeDetail">
            <div class="bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-auto modal-transition"
                :class="{ 'scale-up-center opacity-100': showDetail, 'scale-down-center opacity-0': !showDetail }">

                <div class="relative p-6">
                    <!-- 模态框头部 -->
                    <div class="flex justify-between items-start mb-4">
                        <h3 class="text-xl font-bold text-gray-800">{{ isAdding ? '新增切片' : (currentSplitter.title ||
                    '切片详情') }}</h3>
                        <div class="flex space-x-2">
                            <button v-if="!isAdding && !isEditing" @click="startEditing"
                                class="text-blue-500 hover:text-blue-700 transition-colors duration-200 p-1">
                                编辑
                            </button>
                            <button @click="closeDetail"
                                class="text-gray-400 hover:text-gray-600 transition-colors duration-200 p-1">
                                关闭
                            </button>
                        </div>
                    </div>

                    <!-- 详情内容区域 -->
                    <div class="space-y-4">
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">标题</label>
                            <div v-if="!isAdding && !isEditing"
                                class="p-3 bg-gray-50 rounded-lg border border-gray-200">
                                {{ currentSplitter.title }}
                            </div>
                            <input v-else v-model="editedSplitter.title" type="text"
                                class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200"
                                placeholder="请输入标题">
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">内容</label>
                            <div v-if="!isAdding && !isEditing"
                                class="p-3 bg-gray-50 rounded-lg border border-gray-200 min-h-[200px] max-h-[400px] overflow-y-auto">
                                <p>{{ currentSplitter.content }}</p>
                            </div>
                            <textarea v-else v-model="editedSplitter.content" rows="10"
                                class="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200"
                                placeholder="请输入内容"></textarea>
                        </div>
                    </div>

                    <!-- 底部按钮区域 -->
                    <div class="flex justify-end mt-6 space-x-3">
                        <button v-if="(isEditing || isAdding)" @click="cancelEditing"
                            class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors duration-200">
                            取消
                        </button>
                        <button v-if="(isEditing || isAdding)" @click="saveChanges"
                            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors duration-200">
                            {{ isAdding ? '创建切片' : '保存修改' }}
                        </button>
                        <button v-else @click="closeDetail"
                            class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors duration-200">
                            关闭
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { useSplitterApi } from '../../../api/splitter'
import { ElMessage } from 'element-plus';

const route = useRoute();
const isEditing = ref(false);
const showDetail = ref(false);
const isAdding = ref(false);
const splitterApi = new useSplitterApi();
const documentId = ref(route.query.docId);
const splitterTotalCnt = ref(10);
const currentSplitter = ref({});
const editedSplitter = ref({});
const splitterPageQueryDTO = ref({
    docId: documentId.value,
    page: 1,
    pageSize: 9,
    keyWord: null
})

// splitter列表
const splitterList = ref([]);

// 删除按钮点击事件
const handleDelete = (id) => {
    splitterApi.deleteSplitter(id).then(response => {
        if (response.data.code == 1) {
            ElMessage.success("删除成功！");
            getSplitters();
        } else {
            ElMessage.error(response.data.message);
        }
    }).catch(error => {
        console.error(error);
    })
}

// 请求切片数据
const getSplitters = () => {
    // 清空缓存
    splitterList.value = [];
    splitterApi.getSplitterPage(splitterPageQueryDTO.value).then(response => {
        if (response.data.code == 1) {
            let dataList = response.data.data.dataList;
            splitterTotalCnt.value = response.data.data.total;
            for (const index in dataList) {
                splitterList.value.push({
                    id: dataList[index].id,
                    title: dataList[index].content.replace(/[^\u4e00-\u9fa5]/g, '').substring(0, 6),
                    docId: documentId.value,
                    content: dataList[index].content,
                    imageUrls: dataList[index].imageUrls
                });
            }
            console.log(response.data.data);
        } else {
            ElMessage.error(response.data.message);
        }
    })
}

// 查看详情按钮点击事件
const handleViewDetails = (index) => {
    currentSplitter.value = splitterList.value[index];
    editedSplitter.value = currentSplitter.value;
    showDetail.value = true;
    isEditing.value = false;
    isAdding.value = false;
};

// 开始新增
const handleAddNew = () => {
    // 新切片对象
    const newSplitter = {
        id: null, // 使用时间戳作为临时ID
        title: null,
        content: null,
        docId: documentId.value,
        imageUrls: null
    };
    currentSplitter.value = newSplitter;
    editedSplitter.value = newSplitter;
    showDetail.value = true;
    isEditing.value = false;
    isAdding.value = true;
}

// 开始编辑
const startEditing = () => {
    isEditing.value = true;
};

// 取消事件
const cancelEditing = () => {
    // 新增状态取消直接关闭
    if (isAdding.value) {
        closeDetail();
    }
    editedSplitter.value = currentSplitter.value;
    isEditing.value = false;
};

// 保存修改/创建切片
const saveChanges = () => {
    if (isEditing.value) {
        splitterApi.updateSplitter(editedSplitter.value).then(response => {
            if (response.data.code == 1) {
                ElMessage.success("修改成功");
                isEditing.value = false;
            } else {
                ElMessage.error(response.data.message);
            }
        }).catch(error => {
            console.error(error);
        })
    } else {
        splitterApi.addSplitter(editedSplitter.value).then(response => {
            if (response.data.code == 1) {
                ElMessage.success("新增成功");
                isAdding.value = false;
                showDetail.value = false;
            } else {
                ElMessage.error(response.data.message);
            }
        }).catch(error => {
            console.error(error);
        })
    }
};

// 关闭模态框
const closeDetail = () => {
    showDetail.value = false;
    isEditing.value = false;
    isAdding.value = false;
};

onMounted(() => {
    getSplitters();
});
</script>

<style scoped></style>